//
//  ZooLoginScreen.m
//  ZooNgonDoiOS
//
//  Created by Anh Jun Linh Tinh on 6/1/12.
//  Copyright (c) 2012 Personal. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "ZooLoginScreen.h"
#import "Constants.h"
#import "NearByController.h"
#import "ZooBeanLogin.h"
#import "ZooNetwork.h"
#import "CheckInTask.h"
#import <RestKit/RKJSONParserJSONKit.h>
#import "CreateReviewTask.h"
#import "DetailViewController.h"
#import "ZooSpotBean.h"
#import "MainViewController.h"

@implementation ZooLoginScreen
@synthesize _navigationBar;
//@synthesize changeViewDelegate;
@synthesize txtUsername = _txtUsername;
@synthesize txtPassword = _txtPassword;

- (id)initWithFrame:(CGRect)frame controller:(ZooLoginController *)pZooLoginController
{
    self = [super initWithFrame:frame style:UITableViewStyleGrouped];
    if (self) {
        
        [self setScrollEnabled:NO];
        self.userInteractionEnabled = YES;
        
        //Setup image for view
        UIImage *backgroundImg = [UIImage imageNamed:BackgroundImageConstants];
        self.backgroundColor = [UIColor colorWithPatternImage:backgroundImg];
        [backgroundImg release];
        _zooLoginController = pZooLoginController;
        [self setupView2];
    }
    return self;
}

- (NSInteger)numberOfSections {
    return 0;
}

- (void) setupView2 {
    _vIcon = [[UIImageView alloc]initWithFrame:CGRectMake((self.bounds.size.width - 173) /2, 5, 173, 144)];
    [_vIcon setImage:[UIImage imageNamed:Image_logo]];
    
    UIView *vLogin = [[UIView alloc]initWithFrame:CGRectMake((self.bounds.size.width - 240) /2, 160, 248, 94)];
    _txtUsername = [[UITextField alloc]initWithFrame:CGRectMake(8, 15, 230, 35)];
    [_txtUsername setPlaceholder:NSLocalizedString(@"Email", @"")];
    [_txtUsername setAutocorrectionType:UITextAutocorrectionTypeNo];
    [_txtUsername setFont:[UIFont fontWithName:@"Georgia" size:15]];
    _txtUsername.delegate = self;
    
    _txtPassword = [[UITextField alloc]initWithFrame:CGRectMake(8, 60, 205, 40)];
    [_txtPassword setPlaceholder:NSLocalizedString(@"Password", @"")];
    [_txtPassword setAutocorrectionType:UITextAutocorrectionTypeNo];
    [_txtPassword setSecureTextEntry:YES];
    [_txtPassword setFont:[UIFont fontWithName:@"Georgia" size:15]];
    _txtPassword.delegate = self;
    
    _btnForgotpass = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    [_btnForgotpass setBackgroundImage:[UIImage imageNamed:Image_button_background] forState:UIControlStateNormal];
    [_btnForgotpass setBackgroundImage:[UIImage imageNamed:Image_btnForgot_clicked] forState:UIControlEventTouchUpInside];
    [_btnForgotpass setFrame:CGRectMake(220, 56, 11, 19)];
    
    [vLogin addSubview:_txtUsername];
    [vLogin addSubview:_txtPassword];
    [vLogin addSubview:_btnForgotpass];
    vLogin.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:Image_vLogin_background]];
    
    _btnLogin = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
    [_btnLogin setFrame:CGRectMake((self.bounds.size.width - 193) /2, 260, 193, 47)];
    [_btnLogin setBackgroundImage:[UIImage imageNamed:Image_btnLogin_background] forState:UIControlStateNormal];
    [_btnLogin setBackgroundImage:[UIImage imageNamed:Image_btnLogin_clicked] forState:UIControlEventTouchUpInside];
    [_btnLogin addTarget:self action:@selector(loginClicked) forControlEvents:UIControlEventTouchUpInside];
    _btnLogin.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    _btnSignUp = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
    [_btnSignUp setFrame:CGRectMake((self.bounds.size.width - 139) /2, 410, 139, 39)];
    [_btnSignUp setBackgroundImage:[UIImage imageNamed:Image_btnSignup_background] forState:UIControlStateNormal];
    [_btnSignUp setBackgroundImage:[UIImage imageNamed:Image_btnSignup_clicked] forState:UIControlEventTouchUpInside];
    [_btnSignUp addTarget:self action:@selector(signUpClicked) forControlEvents:UIControlEventTouchUpInside];

    [_txtUsername setText:@"duynt"];
    [_txtPassword setText:@"papahotel"];
    
    [self addSubview:_vIcon];
    [self addSubview:vLogin];
    [self addSubview:_btnLogin];
    [self addSubview:_btnSignUp];
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
//    [self setContentSize:CGSizeMake(320, 100)];
    [self setContentOffset:CGPointMake(0, 150) animated:YES];
    [_btnSignUp setFrame:CGRectMake((self.bounds.size.width - 139) /2, 345, 139, 39)];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *doneButtonCharacterSet = [NSCharacterSet newlineCharacterSet];
    NSRange replacementTextRange = [string rangeOfCharacterFromSet:doneButtonCharacterSet];
    NSUInteger location = replacementTextRange.location;
    
    if (_txtUsername.text.length + string.length > 20){
        if (location != NSNotFound){
            [_txtUsername resignFirstResponder];
        }
        return NO;
    }
    else if (location != NSNotFound){
        [_txtUsername resignFirstResponder];
        [_txtPassword resignFirstResponder];
        return NO;
    }
    return YES;
}
- (void) setupView {
    formLoginBackground = [[UIImageView alloc] initWithFrame:CGRectMake(10, 30, 300, 130)];
    UIImage *backgroundLoginFormImage = [UIImage imageNamed:BackgroundFormLoginConstants];
    [formLoginBackground setImage:backgroundLoginFormImage];
    [backgroundLoginFormImage release];
    
    _txtUsername = [[UITextField alloc] initWithFrame:CGRectMake((self.bounds.size.width - 250) / 2, 60, 250, 30)];
    [_txtUsername setPlaceholder:NSLocalizedString(@"Email", @"")];
    [_txtUsername setAutocorrectionType:UITextAutocorrectionTypeNo];
    
    
    _txtPassword = [[UITextField alloc] initWithFrame:CGRectMake((self.bounds.size.width - 250) / 2, 105, 250, 30)];
    [_txtPassword setPlaceholder:NSLocalizedString(@"Password", @"")];
    [_txtPassword setSecureTextEntry:YES];
    
    //Setup Login button
    _btnLogin = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    
    //Set rounded button
    _btnLogin.layer.cornerRadius = 5;
    [[_btnLogin layer] setMasksToBounds:YES];
    [_btnLogin setOpaque:YES];
    
    [_btnLogin setFrame:CGRectMake((self.bounds.size.width - 220) / 2, 170, 220, 40)];
    [_btnLogin setBackgroundImage:[UIImage imageNamed:ButtonGreenNormal] forState:UIControlStateNormal];
    [_btnLogin setTitle:LoginTextConstants forState:UIControlStateNormal];
    [_btnLogin addTarget:self action:@selector(loginClicked) forControlEvents:UIControlEventTouchUpInside];
    _btnLogin.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    //Setup signup button
    _btnSignUp = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    _btnSignUp.layer.cornerRadius = 5;
    _btnSignUp.clipsToBounds = YES;
    
    [_btnSignUp setFrame:CGRectMake((self.bounds.size.width - 150) / 2, self.bounds.size.height - 100, 150, 40)];
    [_btnSignUp setBackgroundImage:[UIImage imageNamed:ButtonGreenNormal] forState:UIControlStateNormal];
    [_btnSignUp setTitle:SignupTextConstants forState:UIControlStateNormal];
    [_btnSignUp addTarget:self action:@selector(signUpClicked) forControlEvents:UIControlEventTouchUpInside];
    _btnSignUp.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    _btnTest = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnTest.frame = CGRectMake(50, 250, 100, 40);
    [_btnTest setTitle:@"TEST" forState:UIControlStateNormal];
    [_btnTest addTarget:self action:@selector(btnTestClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [_txtUsername setText:@"duynt"];
    [_txtPassword setText:@"papahotel"];
    //Attach subview to view
    [self addSubview:formLoginBackground];
    [self addSubview:_txtUsername];
    [self addSubview:_txtPassword];
    [self addSubview:_btnLogin];
    [self addSubview:_btnSignUp];
    [self addSubview:_btnTest];
    
    [_txtUsername release];
    [_txtPassword release];
    [_btnLogin release];
    [_btnSignUp release];
}

- (void) btnTestClicked {
    CheckInTask *task = [[CheckInTask alloc] initWithSpotId:@"4fcb479933929a1b73000004"];
    [task doExcute];
//    CreateDishTask *task = [[CreateDishTask alloc] initWithParam:@"TEST TEST" spotId:@"Test 111"];
//    CreateReviewTask *task = [[CreateReviewTask alloc] initWithContent:@"Test content" spotId:@""];
//    [task doExecute];
    NSLog(@"TEST");
}

- (void) customizeNavigationBar: (UINavigationController*) navigationController {
    _navigationBar = navigationController.navigationBar;
    [_navigationBar setBackgroundImage:[UIImage imageNamed:NavigationBarBackground] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *logoImg = [UIImage imageNamed:NavigationBarLogo];
    UIImageView* navigationBackgroundImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:NavigationBarLogo]];
    [navigationBackgroundImg setFrame:CGRectMake((_navigationBar.bounds.size.width - logoImg.size.width) / 2, (_navigationBar.bounds.size.height - logoImg.size.height) / 2 + 5, logoImg.size.width, logoImg.size.height)];
    
    UIImage *topPagePattern = [UIImage imageNamed:NavigationTopPagePattern];
    UILabel *topPagePatternLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _navigationBar.bounds.size.height + 6, _navigationBar.bounds.size.width, 7)];
    topPagePatternLabel.backgroundColor = [UIColor colorWithPatternImage:topPagePattern];
    

    [_navigationBar addSubview:navigationBackgroundImg];
    [_navigationBar addSubview:topPagePatternLabel];
}

//========= Event handler ==========//
- (void) loginClicked {
    [self hideVirtualKeyboard];
    
    if ([ZooBeanLogin validateUser:_txtUsername.text password:_txtPassword.text]) {
        [[ZooNetwork sharedNetwork] requestLogin:_txtUsername.text password:_txtPassword.text];
        [self loginSuccessed];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Lỗi dăng nhập" message:@"Tên và mật khẩu chưa đúng" delegate:self cancelButtonTitle:@"Nhập lại" otherButtonTitles:nil];
        
        [alert show];
    }
}

- (void) loginSuccessed {
    _homeViewController = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];
    [_zooLoginController.navigationController pushViewController:_homeViewController animated:YES];
    
    
//    MainViewController *mainViewController = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
//    [_zooLoginController.navigationController pushViewController:mainViewController animated:YES];
    
//    ZooSpotBean *_mSpot = [[ZooSpotBean alloc] init];
//    _mSpot.name = @"abc";
//    DetailViewController *detailViewController = [[DetailViewController alloc]initWithSpot:_mSpot];
//    detailViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//    [_zooLoginController.navigationController pushViewController:detailViewController animated:YES];
    
//    [_zooLoginController.navigationController setNavigationBarHidden:YES];
}

- (void) signUpClicked {
    [self hideVirtualKeyboard];
    _zooSignUpViewController = [[ZooSignUpViewController alloc]initWithNibName:@"ZooSignUpViewController" bundle:nil];
    [_zooLoginController.navigationController pushViewController:_zooSignUpViewController animated:YES];
    [_zooLoginController.navigationController setNavigationBarHidden:YES];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self hideVirtualKeyboard];
    [_btnSignUp setFrame:CGRectMake((self.bounds.size.width - 139) /2, 410, 139, 39)];
}

- (void) hideVirtualKeyboard {
    [_txtUsername resignFirstResponder];
    [_txtPassword resignFirstResponder];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
